<template>
  <el-card>
    <div class="title">
      <span>添加菜品</span>
      <el-button type="text" @click="fanhui" class="fanhui">返回</el-button>
    </div>
    <el-form ref="addDishRef" :model="addDishForm" label-width="120px" :rules="addDishRules">
      <el-form-item label="菜品名称" prop="dishName">
        <el-input v-model="addDishForm.dishName" clearable placeholder="请输入菜品名称" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="所属商家名称" prop="shopId">
        <el-select v-model="addDishForm.shopId" placeholder="请选择商家" style="width: 300px" @change="changeShop(addDishForm.shopId)">
          <el-option v-for="(item, index) in shopList" :key="index" :label="item.shopName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属菜品分类" prop="categoryId">
        <el-select v-model="addDishForm.categoryId" placeholder="请选择菜品分类" style="width: 300px">
          <el-option v-for="(item, index) in categoryList" :key="index" :label="item.categoryName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="菜品价格" prop="dishPrice">
        <el-input v-model="addDishForm.dishPrice" clearable placeholder="请输入菜品价格" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="规格配置">
        <el-button type="primary" @click="addFlavore" v-if="dishFlavore.length == 0">添加口味</el-button>
        <div class="flavore" v-if="dishFlavore.length != 0">
          <div class="count" v-for="(item, index) in dishFlavore" :key="index">
            <el-select
              clearable
              v-model="item.name"
              placeholder="请设置口味"
              style="width: 150px; margin-bottom: 10px"
              @change="change(index, item.name)"
              @clear="delArray(index)"
            >
              <el-option v-for="(it, int) in flavors" :key="int" :label="it.name" :value="it.name"></el-option>
            </el-select>
            <div class="labal">
              <el-tag
                disable-transitions
                v-for="(it, int) in item.value"
                :key="int"
                closable
                style="margin-right: 10px; margin-bottom: 10px"
                @close="delLabel(it, index)"
                >{{ it }}</el-tag
              >
            </div>
          </div>
          <div class="fotter">
            <el-button type="primary" @click="addFlavore">添加口味</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="图片上传" prop="dishImage">
        <el-upload
          class="upload-demo"
          action="http://localhost:8080/school/image/upload"
          :on-success="uploadSuccess"
          :on-remove="deleteImage"
          :before-upload="beforeUpload"
          style="width: 300px"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过3MB</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="菜品简介" prop="dishText">
        <el-input type="textarea" v-model="addDishForm.dishText" clearable placeholder="请输入菜品简介" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: 'AddDish',
  data() {
    var checkPrice = (rules, value, callback) => {
      {
        const reg = /^\d+(\.\d{0,2})?$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error('菜品价格格式只能为数字,且最多保留两位小数'));
        }
      }
    };

    return {
      addDishForm: {
        dishName: '',
        dishPrice: '',
        dishText: '',
        dishImage: '',
        categoryId: '',
        userName: '',
        shopId: '',
      },
      info: [],
      addDishRules: {
        dishName: [
          {
            required: true,
            message: '请输入菜品名称',
            trigger: 'blur',
          },
        ],
        categoryId: [
          {
            required: true,
            message: '请选择菜品分类',
            trigger: 'blur',
          },
        ],
        shopId: [
          {
            required: true,
            message: '请选择菜品分类',
            trigger: 'blur',
          },
        ],
        dishText: [
          {
            required: true,
            message: '请选择菜品简介',
            trigger: 'blur',
          },
        ],
        dishPrice: [
          {
            required: true,
            message: '菜品价格不能为空',
            trigger: 'blur',
          },
          { validator: checkPrice, trigger: 'blur' },
        ],
        dishImage: [{}],
      },
      //获取菜品分类列表
      categoryList: [],
      //商家列表数据
      shopList: [],
      dishFlavore: [],
      flavors: [],
    };
  },
  mounted() {
    this.info = JSON.parse(localStorage.getItem('userinfo'));
    this.addDishForm.userName = this.info.userName;
  },
  created() {
    this.getShopList();
    this.getFlavors();
  },

  methods: {
    beforeUpload(file) {
      console.log(file);
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1);

      const whiteList = ['jpg', 'png'];

      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.error('上传文件只能是 jpg、png 格式');
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 3;

      if (!isLt2M) {
        return this.$message.error('上传文件大小不能超过 3MB，请选择其他图片');
      }
    },
    change(index, name) {
      for (let j = 0; j < this.dishFlavore.length - 1; j++) {
        if (this.dishFlavore[j].name === name) {
          this.delArray(index);
          this.$message.error('该口味信息已存在请重新输入');
        }
      }
      let value;
      for (let i = 0; i < this.flavors.length; i++) {
        if (this.flavors[i].name == name) {
          value = this.flavors[i].value;
        }
      }
      this.dishFlavore[index].value = value;
    },
    delArray(index) {
      this.dishFlavore.splice(index, 1);
    },
    delLabel(int, index) {
      this.dishFlavore[index].value.splice(this.dishFlavore[index].value.indexOf(int), 1);
    },
    getFlavors() {
      this.flavors = [
        {
          name: '甜味',
          value: ['无糖', '少糖', '半糖', '多糖', '全糖'],
        },
        {
          name: '温度',
          value: ['热饮', '常温', '去冰', '少冰', '多冰'],
        },
        {
          name: '忌口',
          value: ['不要葱', '不要蒜', '不要香菜', '不要辣'],
        },
        { name: '辣度', value: ['不辣', '微辣', '中辣', '重辣'] },
      ];
    },
    //接受上传成功的返回的图片名称
    uploadSuccess(reponse) {
      this.addDishForm.dishImage = reponse.data;
      return this.$message.success('上传成功');
    },
    //取消上传后删除图片
    async deleteImage() {
      const { data: res } = await this.$http.delete('image/deleteImage/' + this.addDishForm.dishImage);
      if (res.code == 1) {
        return this.$message.success(res.data);
      } else {
        return this.$message.error(res.msg);
      }
    },
    //获取分类列表
    async changeShop(shopId) {
      console.log(shopId);
      const { data: res } = await this.$http.get('dish/getCategoryList/' + shopId);
      if (res.code == 1) {
        this.categoryList = res.data;
      } else {
        return this.$message.error('请求失败');
      }
    },
    //获取商家列表
    async getShopList() {
      const { data: res } = await this.$http.get('dish/getShopList');
      if (res.code == 1) {
        this.shopList = res.data;
      } else {
        return this.$message.error('信息获取失败');
      }
    },
    //提交新增菜品信息
    submitForm() {
      this.$refs.addDishRef.validate(async (valid) => {
        if (valid) {
          for (let i = 0; i < this.dishFlavore.length; i++) {
            this.dishFlavore[i].value = JSON.stringify(this.dishFlavore[i].value);
          }
          this.addDishForm.dishFlavore = this.dishFlavore;
          this.dishFlavore = [];
          const { data: res } = await this.$http.post('dish/addDish', this.addDishForm);
          if (res.code == 1) {
            this.$router.push('/meals');
            return this.$message.success(res.data);
          } else {
            return this.$message.error(res.msg);
          }
        } else {
          return this.$message.error('表单信息校验失败');
        }
      });
      console.log(this.addDishForm);
    },
    //重置表单
    resetForm() {
      this.$refs.addDishRef.resetFields();
    },
    //返回按钮
    fanhui() {
      this.$router.go(-1);
    },
    addFlavore() {
      this.dishFlavore.push({ name: '', value: '' });
    },
  },
};
</script>

<style lang="scss" scoped>
.title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 30px;
  display: flex;
  justify-content: space-between;
}
.fanhui {
  font-size: 15px;
  font-weight: bold;
}
</style>